package com.wxm.jwt.service.util;

import com.alibaba.fastjson.JSONObject;
import com.wxm.jwt.exception.JWTException;
import com.wxm.jwt.service.properties.JWTAuthService;
import com.wxm.jwt.util.JwtHelper;
import lombok.AllArgsConstructor;
import java.util.function.Supplier;

/**
 * <p>
 *      JwtToken 服务端工具
 * </p>
 *
 * @author: wxm
 * @Date: 2021/10/6
 */
@AllArgsConstructor
public class JwtTokenServiceUtil {
    /**
     *  从supplier中获取JWTAuthClient
     */
    private final Supplier<? extends JWTAuthService> supplier;

    /**
     * 生成Token
     * @param jsonUser 用户信息
     * @param second 秒数 如果second不为null则取当前参数 否则取 {@link JWTAuthService#getExpireSecond()}
     * @return String
     */
    public String generateToken(JSONObject jsonUser,Integer second) {
        try {
            JWTAuthService jwtAuthClient = supplier.get();
            return JwtHelper.generateToken(jsonUser,jwtAuthClient.getPrivateKey(),second != null ? second : jwtAuthClient.getExpireSecond());
        }catch (Exception e){
            JWTException.error("私钥生成失败：" + e.getMessage());
        }
        return null;
    }

    /**
     * 解析Token
     * @param token token字符串
     * @param tClass 期待解析后类型
     * @param <T> T
     * @return T类型对象
     */
    public <T> T getUserInfo(String token,Class<T> tClass) {
        try {
            JWTAuthService jwtAuthClient = supplier.get();
            return JwtHelper.getJwtFromToken(token,jwtAuthClient.getPublicKey(),tClass);
        }catch (Exception e){
            JWTException.error("私钥生成失败：" + e.getMessage());
        }
        return null;
    }
}
